package com.mxpio.erp.equipment.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.mxpio.erp.common.equipment.entity.EquipmentEqpAttr;
import com.mxpio.erp.common.equipment.entity.EquipmentEqpBasics;
import com.mxpio.erp.common.equipment.entity.VEquipmentEqp;
import com.mxpio.erp.common.equipment.service.EquipmentEqpBasicsService;
import com.mxpio.erp.common.equipment.service.VEquipmentEqpService;
import com.mxpio.erp.equipment.utils.QRCodeUtil;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;


@Tag(name = "EquipmentEqpBasicsController}", description = "设备台账")
@RestController
@RequestMapping("/erp/equipment/eqp/")
public class EquipmentEqpBasicsController {

    @Autowired
    private EquipmentEqpBasicsService equipmentEqpBasicsService;

    @Autowired
    private VEquipmentEqpService equipmentEqpService;


    @GetMapping("list")
    @Operation(summary = "设备台账列表", description = "获取设备台账列表（无分页）", method = "GET")
    public Result<List<EquipmentEqpBasics>> list(@Parameter(description = "查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<EquipmentEqpBasics> list = equipmentEqpBasicsService.list(EquipmentEqpBasics.class, criteria);
        return Result.OK(list);
    }

    @GetMapping("page")
    @Operation(summary = "设备台账列表", description = "获取设备台账列表（分页）", method = "GET")
    public Result<Page<EquipmentEqpBasics>> page(@Parameter(description = "查询参数") Criteria criteria, @Parameter(description = "每页条数") Integer pageSize, @Parameter(description = "页号") Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo - 1, pageSize);
        Page<EquipmentEqpBasics> pageResult = equipmentEqpBasicsService.listPage(EquipmentEqpBasics.class, page, criteria);
        return Result.OK(pageResult);
    }

    @GetMapping("list/{id}")
    @Operation(summary = "根据ID获取设备台账列表", description = "根据ID获取设备台账列表", method = "GET")
    public Result<EquipmentEqpBasics> listById(@PathVariable(name = "id", required = true) String id) {
        EquipmentEqpBasics equipmentEqpBasics = equipmentEqpBasicsService.getById(EquipmentEqpBasics.class, id);
        return Result.OK(equipmentEqpBasics);
    }

    @GetMapping("code/{code}")
    @Operation(summary = "根据eqpCode获取设备台账信息", description = "根据code获取设备台账信息", method = "GET")
    public Result<EquipmentEqpBasics> getByCode(@PathVariable(name = "code", required = true) String code) {
        EquipmentEqpBasics equipmentEqpBasics = equipmentEqpBasicsService.getByCode(code);
        return Result.OK(equipmentEqpBasics);
    }

    @RequestMapping("add")
    @Operation(summary = "保存设备台账", description = "保存设备台账")
    public Result<EquipmentEqpBasics> add(@RequestBody EquipmentEqpBasics equipmentEqpBasics) {
        equipmentEqpBasicsService.saveEqp(equipmentEqpBasics);
        return Result.OK(equipmentEqpBasics);
    }

    @PutMapping("edit")
    @Operation(summary = "编辑设备台账", description = "编辑设备台账", method = "PUT")
    public Result<EquipmentEqpBasics> edit(@RequestBody EquipmentEqpBasics equipmentEqpBasics) {
        equipmentEqpBasicsService.updateEqpById(equipmentEqpBasics);
        return Result.OK(equipmentEqpBasics);
    }

    @PutMapping("bindNFC")
    @Operation(summary = "设备基本信息-绑定NFC", description = "设备基本信息-绑定NFC", method = "PUT")
    public Result<?> bindNFC(@RequestBody EquipmentEqpBasics equipmentEqpBasics) {
        if (StringUtils.isBlank(equipmentEqpBasics.getId())) {
            return Result.error("设备ID为空");
        }
        equipmentEqpBasicsService.bindNFC(equipmentEqpBasics);
        return Result.OK("绑定成功!");
    }

    @PutMapping("bindNFCList")
    @Operation(summary = "设备基本信息-绑定NFCList", description = "设备基本信息-绑定NFCList", method = "PUT")
    public Result<?> bindNFCList(@RequestBody Map map) {
        String listStr = map.get("listStr") + "";
        if (StringUtils.isBlank(listStr)) {
            return Result.error("参数为空");
        }
        String result = equipmentEqpBasicsService.bindNFCList(listStr);
        if (StringUtils.isBlank(result)) {
            return Result.OK("绑定成功!");
        }
        return Result.error(result);
    }

    @GetMapping("getImg")
    @Operation(summary = "设备基本信息-获取区域二维码", description = "设备基本信息-获取区域二维码", method = "GET")
    public Result<?> getImg(String id) {
        EquipmentEqpBasics basics = equipmentEqpBasicsService.getById(EquipmentEqpBasics.class, id);
        JSONObject object = new JSONObject();
        object.put("id", id);
        object.put("eqpName", basics.getEqpName());
        object.put("eqpCode", basics.getEqpCode());
        String base64 = null;
        try {
            base64 = QRCodeUtil.getImageBase64(JSONUtil.toJsonStr(object));
        } catch (Exception e) {
            return Result.error("生成失败！");
        }

        return Result.OK(base64);
    }

    @DeleteMapping("remove/{ids}")
    @Operation(summary = "根据id删除设备台账", description = "删除设备台账,多个id用英文逗号分隔", method = "DELETE")
    public Result<EquipmentEqpBasics> remove(@PathVariable(name = "ids", required = true) String ids) {
        String[] id = ids.split(",");
        for (String key : id) {
            equipmentEqpBasicsService.delete(EquipmentEqpBasics.class, key, new SmartCrudPolicyAdapter() {
                @Override
                public boolean beforeDelete(CrudContext context) {
                    Object o = context.getEntity();
                    if (o instanceof EquipmentEqpBasics) {
                        try {
                            JpaUtil.lind(EquipmentEqpAttr.class).equal("eqpId", ((EquipmentEqpBasics) o).getId()).delete();
                        } catch (Exception e) {
                            return false;
                        }
                    }
                    return true;
                }
            });
        }
        return Result.OK();
    }

    @GetMapping("popup/page")
    @Operation(summary = "设备台账列表-设备视图", description = "获取设备台账列表-设备视图（分页）", method = "GET")
    public Result<Page<VEquipmentEqp>> popupPage(@Parameter(description = "查询参数") Criteria criteria, @Parameter(description = "每页条数") Integer pageSize, @Parameter(description = "页号") Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo - 1, pageSize);
        Page<VEquipmentEqp> pageResult = equipmentEqpService.listPage(page, criteria);
        return Result.OK(pageResult);
    }


}
